<template>
    <div class="recycle-wrap">
        <el-card style="margin: 10px;">
            <div style="width: 73%;">
                <el-row>
                    <el-form ref="queryForm" :model="queryParams">
                        <el-col :span="5">
                            <el-form-item prop="productId">
                                <el-select v-model="queryParams.productId" placeholder="请选择产品" style="width: 95%"
                                    clearable filterable>
                                    <el-option v-for="item in productList" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item prop="deviceName">
                                <el-input :placeholder="'设备名称'" clearable v-model="queryParams.deviceName"
                                    style="width: 95%">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item prop="deviceName">
                                <el-input :placeholder="'设备编号'" clearable v-model="queryParams.serialNumber"
                                    style="width: 95%">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询
                            </el-button>
                        </el-col>
                        <el-button icon="el-icon-refresh-left" @click="resetQuery"
                            style="margin-left: 5px;">重置</el-button>
                    </el-form>
                </el-row>
            </div>
            <div class="general">
                <div class="topLeft">
                    <div style="padding:10px 10px;background-color:#f8f8f9;">
                        <span style="font-size:15px;font-weight:bold;">设备列表</span>
                        <span style="font-size:15px;font-weight:bold;float:right">{{ selectedCount
                            }}/{{ this.count }}</span>
                    </div>
                    <el-row>
                        <el-table ref="leftTableData" :data="menuTableData" style="width: 100%" height="373" max-height="373"
                            @selection-change="changeCheckBoxValueLeft">
                            <template slot="empty">
                                <el-empty :image-size="100" description="暂无数据"></el-empty>
                            </template>
                            <el-table-column type="selection" align="center" width="40"
                                :selectable="checkSelectable"></el-table-column>
                            <el-table-column v-if="false" prop="deviceId" label="DeviceKey" fixed
                                show-overflow-tooltip></el-table-column>
                            <el-table-column  prop="deviceName"  label="设备名称" fixed
                                show-overflow-tooltip></el-table-column>
                            <el-table-column prop="serialNumber" label="设备编号" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="productName" label="所属产品" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column label="状态" prop="status" width="80">
                                <template slot-scope="scope">
                                    <dict-tag :options="dict.type.iot_device_status" :value="scope.row.status" size="small" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                </div>
                <div class="topCenter">
                    <el-button type="primary" :disabled="add" @click="rightAdd"><i
                            class="el-icon-arrow-right el-icon--right"></i></el-button>
                    <el-button type="primary" :disabled="del" @click="leftDelete"><i
                            class="el-icon-arrow-left el-icon--left"></i></el-button>
                </div>
                <div class="topRight">
                    <div style="padding:10px 10px;background-color:#f8f8f9;">
                        <span style="font-size:15px;font-weight:bold;">已绑定设备</span>
                        <!-- <span style="font-size:15px;font-weight:bold;float:right">{{ selectedCount1 }}/500</span> -->
                    </div>
                    <el-row>
                        <el-table ref="rightTableData" :data="rightTableData" style="width: 100%" height="373" max-height="373"
                            @selection-change="changeCheckBoxValueRight">
                            <template slot="empty">
                                <el-empty :image-size="100" description="暂无数据"></el-empty>
                            </template>
                            <el-table-column type="selection" align="center" width="40"></el-table-column>
                            <el-table-column  v-if="false" prop="deviceId" label="DeviceKey" fixed
                                show-overflow-tooltip></el-table-column>
                            <el-table-column prop="deviceName" label="设备名称" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="serialNumber" label="设备编号" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="productName" label="所属产品" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column label="状态" align="center" prop="status" width="80">
                                <template slot-scope="scope">
                                    <dict-tag :options="dict.type.iot_device_status" :value="scope.row.status" size="small" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                </div>
            </div>
            <div class="pagination-container">
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :pager-count="5"
                    :limit.sync="queryParams.pageSize" :pageSizes="[10, 20, 30, 40]" @pagination="getList" />
            </div>
        </el-card>
    </div>
</template>
<script type="text/javascript">
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    // import { deptsTreeSelectSub } from "@/api/system/user";
    import { findTiePointDeviceByTiePointId} from "@/api/subsystem/tiepointDevice";//查询子系统的绑点关联关系
    import { listDevice, recycleDevice } from "@/api/iot/device";
    import {
        listProduct
    } from "@/api/iot/product";
    export default {
        dicts: ['iot_device_status'],
        props: {
            dragGaTiepointId: {
                type: Number,
                required: true
            }
        },
        components: {
            Treeselect
        },
        data() {
            return {
                productList: [],
                total: 0,
                count: 0,
                productList: [],
                selectedCount: 0,
                queryParams: {
                    productId: null,
                    deviceName: "",
                    pageNum: 1,
                    pageSize: 10,
                    showChild: false,
                },
                //导入表单
                allotForm: {
                    productId: 0,
                    deptId: 0,
                },
                deviceIds: {},
                // 机构树选项
                deptOptions: [],
                add: true,
                del: true,
                leftTableData: [],
                rightTableData: [],
                selectedListLeft: [], //点击左边选中的
                selectedListRight: [], //点击右边选中的
                menuTableData: [],
                //导入分配表单校验
                allotRules: {
                    deptId: [{ required: true, message: '回收机构不能为空', trigger: 'change' }],
                },
            };
        },
        created() {
            this.getProductList();
            //this.getDeptTree();
            this.getList();
        },
        computed: {
            selectedCount1() {
                return this.rightTableData.length;
            }
        },
        watch: {
            selectedListLeft: function (val) {
                if (val.length) {
                    this.add = false;
                } else {
                    this.add = true;
                }
            },
            selectedListRight: function (val) {
                if (val.length) {
                    this.del = false;
                } else {
                    this.del = true;
                }
            },
        },
        methods: {
            //查询所有设备列表
            getList() {
                this.loading = true;
                listDevice(this.queryParams).then(response => {
                    this.menuTableData = response.rows;
                    //isSelect用于判断是否可选
                    this.menuTableData.map(item => {
                        this.leftTableData.push(Object.assign(item, {
                            isSelect: 0
                        }))
                    })
                     if(this.dragGaTiepointId != undefined){
                        findTiePointDeviceByTiePointId(this.dragGaTiepointId).then((response) => {
                            if(response.code == 200){
                                if(response.data != undefined){
                                    console.log(response.data.deviceId)
                                    let leftTableData = JSON.parse(JSON.stringify(this.menuTableData));
                                    leftTableData.forEach((item, index) => {
                                        if (item.deviceId == response.data.deviceId) {
                                            item.isSelect = 1;
                                            //右边数据
                                            this.rightTableData = this.rightTableData
                                                .concat(item)
                                                .sort((a, b) => {
                                                    return a.deviceId - b.deviceId;
                                            });
                                        }
                                    });
                                    this.menuTableData = leftTableData;
                                }
                            }
                        })
                    }


                    // //分页后保持已选中状态
                    // if (this.rightTableData.length != 0) {
                    //     this.menuTableData.forEach((item, index) => {
                    //         this.rightTableData.forEach((item1) => {
                    //             if (item1.deviceId == item.deviceId) {
                    //                 item.isSelect = 1;
                    //             }
                    //         });
                    //     });
                    // }
                    this.total = response.total;
                    if (this.count === 0) {
                        this.count = this.total;
                    }
                    this.loading = false;


                    
                    // this.menuTableData = response.rows;
                    // //isSelect用于判断是否可选
                    // this.menuTableData.map(item => {
                    //     this.leftTableData.push(Object.assign(item, {
                    //         isSelect: 0
                    //     }))
                    // })
                    // // if(this.dragGaTiepointId != undefined){
                    // //     findTiePointDeviceByTiePointId(this.dragGaTiepointId).then((response) => {
                    // //         if(response.code == 200){
                    // //             if(response.data != undefined){
                    // //                 console.log(response.data.tiePointId)
                    // //                 this.$refs.leftTableData.toggleRowSelection(response.data.tiePointId, true);
                    // //             }
                    // //         }
                    // //     })
                    // // }

                    // //分页后保持已选中状态
                    // if (this.rightTableData.length != 0) {
                    //     this.menuTableData.forEach((item, index) => {
                    //         this.rightTableData.forEach((item1) => {
                    //             if (item1.deviceId == item.deviceId) {
                    //                 item.isSelect = 1;
                    //             }
                    //         });
                    //     });
                    // }
                    // this.total = response.total;
                    // if (this.count === 0) {
                    //     this.count = this.total;
                    // }
                    // // this.loading = false;
                });
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.queryParams.productId = null;
                this.rightTableData = [];
                this.resetForm('queryForm');
                this.handleQuery();
            },
            /** 查询产品列表 */
            getProductList() {
                this.loading = true;
                const params = {
                    pageSize: 999,
                }
                listProduct(params).then(response => {
                    this.productList = response.rows.map((item) => {
                        return { value: item.productId, label: item.productName };
                    });

                });
            },

            /** 查询机构下拉树结构 */
            getDeptTree() {
                this.queryParams.deptId = null;
                const showOwner = false;
                deptsTreeSelectSub(showOwner).then(response => {
                    this.deptOptions = response.data;
                });
            },
            /** 返回按钮 */
            goBack() {
                const obj = {
                    path: '/iot/device',
                };
                this.$tab.closeOpenPage(obj);
            },
            //右边增加的数据
            rightAdd() {
                if(this.selectedListLeft.length > 1){
                    this.$modal.msgError("一个子系统图标只能绑定一个设备！");
                }else if(this.rightTableData.length >= 1){
                    this.$modal.msgError("一个子系统图标只能绑定一个设备！");
                }else{
                    let leftTableData = JSON.parse(JSON.stringify(this.menuTableData));
                    leftTableData.forEach((item, index) => {
                        this.selectedListLeft.forEach((item1) => {
                            if (item.deviceId == item1.deviceId) {
                                this.rightTableData = this.rightTableData
                                    .concat(item)
                                    .sort((a, b) => {
                                        return a.deviceId - b.deviceId;
                                    });
                                item.isSelect = 1;
                            }
                        });
                    });
                    if (this.selectedCount1 != 0) {
                        this.count = this.count - this.selectedListLeft.length;
                    }
                    leftTableData = leftTableData.filter((val) => {
                        return val;
                    });
                    this.menuTableData = leftTableData;
                    this.selectedListLeft = []; 
                }
            },
            //删除的数据
            leftDelete() {
                let rightTableData = JSON.parse(JSON.stringify(this.rightTableData));
                rightTableData.forEach((item, index) => {
                    this.selectedListRight.forEach((item1) => {
                        this.menuTableData.forEach((item2) => {
                            if (item2.deviceId == item1.deviceId) {
                                item2.isSelect = 0;
                            }
                            if (item1.deviceId == item.deviceId) {
                                delete rightTableData[index];
                            }
                        });
                    });
                });
                if (this.selectedCount1 != 0) {
                    this.count = this.count + this.selectedListRight.length;
                    //this.getList();
                }
                rightTableData = rightTableData.filter((val) => {
                    return val;
                });
                this.rightTableData = rightTableData;
                this.selectedListRight = [];
            },
            checkSelectable(row) {
                let flag = true
                if (row.isSelect === 0) {
                    flag = true
                } else {
                    flag = false
                }
                return flag
            },

            //左边数据
            changeCheckBoxValueLeft(val) {
                this.selectedListLeft = val;
                this.selectedCount = val.length;
            },
            //右边数据
            changeCheckBoxValueRight(val) {
                this.selectedListRight = val;
            },
            //确定回收操作
            confirmDistribution() {
                this.$refs['allotForm'].validate((valid) => {
                    if (valid) {
                        this.deviceIds = this.rightTableData.map((item) => item.deviceId);
                        const deviceIds = this.deviceIds.join(',');
                        recycleDevice(deviceIds).then(response => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess(response.msg);
                                this.resetQuery();
                            } else {
                                this.$modal.msgError(response.msg);
                            }
                        });
                    }
                });

            },
        },
    };
    </script>
    <style lang="scss" scoped>
    .recycle-wrap {
        height: 100%;
    }

    ::v-deep {
        .topCenter {
            .el-button+.el-button {
                margin-left: 0px;
                margin-top: 10px;
            }
        }
    }

    .changeWords {
        display: inline-block;
        margin: 10px 0;
        font-size: 16px;
        font-weight: bold;
    }

    .general {
        display: flex;
        align-items: center;
    }

    .topLeft {
        width: 45%;
        height: 373px;
        overflow: hidden;
    }

    .topCenter {
        width: 10%;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .topRight {
        width: 45%;
        height: 373px;
        overflow: hidden;
    }

    .pagination-container {
        text-align: left;
        width: 45%;
        margin: 20px 0 100px 115px;
    }
    </style>